package org.app.Service.Impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.app.Entity.*;
import org.app.Entity.comm.Result;
import org.app.Service.IPersonalExercisePlanService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.app.Mapper.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class PersonalExercisePlanService implements IPersonalExercisePlanService {
    @Resource
    private IExercisePlanMapper planMapper;
    @Resource
    private INewTableMapper tableMapper;
    @Resource
    private INewLineMapper lineMapper;
    @Resource
    private IStrengthDataMapper dataMapper;
    @Resource
    private ISaveMapper saveMapper;
    @Resource
    private ISaveSDMapper sdMapper;
    @Resource
    private ISaveTableMapper saveTableMapper;
    @Resource
    private ISaveLineMapper saveLineMapper;

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime now = LocalDateTime.now();
    String formattedTime = now.format(formatter);

    @Override
    public Result<List<ExercisePlan>> listExercisePlanByCIDInTwoDays(String c_id){
        Result<List<ExercisePlan>> result = new Result<>();
        if(planMapper.listExercisePlanByCIDInTwoDays(c_id) == null){
            result.setCode(500);
            result.setMessage("查询出错");
            result.setData(null);
        } else {
            result.setCode(200);
            result.setMessage("查询成功");
            result.setData(planMapper.listExercisePlanByCIDInTwoDays(c_id));
        }
        return result;
    }
    @Override
    public Result<ExercisePlan> listExercisePlanByPID(String p_id){
        Result<ExercisePlan> result = new Result<>();
        if(planMapper.selectById(p_id) == null){
            result.setCode(500);
            result.setMessage("查询出错");
            result.setData(null);
        } else {
            result.setCode(200);
            result.setMessage("查询成功");
            result.setData(planMapper.selectById(p_id));
        }
        return result;
    }

    @Override
    @Transactional
    public Result<Integer> createExercisePlan(List<ExercisePlan> exercisePlanList, String save_id) {

        // 遍历每个 ExercisePlan，逐一处理
        for (ExercisePlan plan : exercisePlanList) {
            // 设置基本属性
            plan.setCreate_time(formattedTime); // 设置创建时间
            plan.setIsGroup(false);            // 设置是否为群组
            plan.setCreator_id(plan.getC_id()); // 设置创建者 ID
            plan.setIsLink(true);              // 设置是否关联
            plan.setCopy(true);                // 设置是否为拷贝

            // 处理时间相关逻辑
            Date date = plan.getP_date(); // 获取计划日期
            LocalTime endTime = plan.getP_endTime(); // 获取计划结束时间
            LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // 转换日期格式
            LocalDateTime dateTime = LocalDateTime.of(localDate, endTime); // 组合日期和时间
            LocalDateTime dateTimeAfter24Hours = dateTime.plusHours(24); // 增加 24 小时

            plan.setEnd_update_time(dateTimeAfter24Hours.format(formatter)); // 设置更新时间

            // 插入计划
            planMapper.createExercisePlan(plan);

            // 插入 StrengthData 数据（如果存在）
            if (plan.getStrengthList() != null && !plan.getStrengthList().isEmpty()) {
                List<StrengthData> dataList = plan.getStrengthList();
                for (StrengthData data : dataList) {
                    data.setP_id(plan.getP_id()); // 关联计划 ID
                    dataMapper.createDataBatch(data); // 插入 StrengthData 数据
                }
            }

            // 插入 NewTable 数据（如果存在）
            if (plan.getTableList() != null && !plan.getTableList().isEmpty()) {
                List<NewTable> tableList = plan.getTableList();
                for (NewTable table : tableList) {
                    table.setP_id(plan.getP_id()); // 关联计划 ID
                    tableMapper.saveNewTable(table); // 插入 NewTable 数据

                    // 插入 NewLine 数据
                    List<NewLine> lineList = table.getLineList();
                    for (NewLine line : lineList) {
                        line.setTable_id(table.getTable_id()); // 关联表格 ID
                    }
                    lineMapper.saveNewLineBatch(lineList); // 批量插入 NewLine 数据
                }
            }
        }

        // 返回结果
        Result<Integer> result = new Result<>();
        result.setCode(200);
        result.setData(1);
        result.setMessage("插入成功");
        return result;
    }


    @Override
    public Result<Integer> updateExercisePlan(ExercisePlan exercisePlan){
        Result<Integer> result = new Result<>();
        // 修改只能在最初创建的结束时间后24小时之内修改，若是已经修改过的还需要二次修改，则仍然按照最初创建的结束时间来控制修改
        String update_time = exercisePlan.getEnd_update_time();
        LocalDateTime endUpdateTime = LocalDateTime.parse(update_time, formatter);
        LocalDateTime endTime = endUpdateTime.minusHours(24);
        if (now.isAfter(endUpdateTime)) {
            result.setCode(500);
            result.setMessage("计划结束已超过24小时,无法修改");
            result.setData(null);
            return result;
        } else if(now.isBefore(endTime)){
            result.setCode(500);
            result.setMessage("计划尚未结束，请之后再修改");
            result.setData(null);
            return result;
        }
        // 保存第一次创建的计划，后续的修改之保存两版，最终也没有更新的计划指向第一次创建的计划了，不太合理
        String origin_id = exercisePlan.getP_id();
        ExercisePlan plan = planMapper.selectById(exercisePlan.getP_id());
        exercisePlan.setOrigin_id(origin_id);
        exercisePlan.setCreate_time(formattedTime);
        exercisePlan.setP_id(null);

        if(!plan.getOrigin_id().isEmpty()) {
            ExercisePlan originPlan = planMapper.getUnShown(plan.getOrigin_id());
            if(originPlan == null){
                log.info("没有原始方法");
            } else {
                List<NewTable> tableList = originPlan.getTableList();
                List<StrengthData> dataList = originPlan.getStrengthList();
                if(dataList != null && dataList.size()>0){
                    for (StrengthData data : dataList){
                        dataMapper.deleteStrengthDataByPID(data);
                    }
                }
                if(tableList != null && tableList.size()>0){
                    for(NewTable table : tableList){
                        List<NewLine> lineList = table.getLineList();
                        for(NewLine line : lineList){
                            lineMapper.deleteNewLineByTableID(line);
                        }
                        tableMapper.deleteNewTableByPID(table);
                    }
                }
                planMapper.deleteExercisePlan(originPlan);
            }
            plan.setOrigin_id(null);
            planMapper.updateExercisePlan(plan);
        }
        planMapper.unshowPlan(plan);

        planMapper.createExercisePlan(exercisePlan);
        if(exercisePlan.getStrengthList()!=null && exercisePlan.getStrengthList().size()>0){
            List<StrengthData> dataList = exercisePlan.getStrengthList();
            for(StrengthData data : dataList){
                data.setS_id(null);
                data.setP_id(exercisePlan.getP_id());
                dataMapper.createDataBatch(data);
            }
        }
        if(exercisePlan.getTableList()!=null && exercisePlan.getTableList().size()>0){
            List<NewTable> tableList = exercisePlan.getTableList();
            for(NewTable table : tableList){
                table.setTable_id(null);
                table.setP_id(exercisePlan.getP_id());
                tableMapper.saveNewTable(table);
                List<NewLine> lineList = table.getLineList();
                for(NewLine line : lineList){
                    line.setLine_id(null);
                    line.setTable_id(table.getTable_id());
                }
                lineMapper.saveNewLineBatch(lineList);
            }
        }

        result.setCode(200);
        result.setData(1);
        result.setMessage("修改成功");
        return result;
    }
    @Override
    public Result<Integer> deleteExercisePlan(String p_id){
        Result<Integer> result = new Result<>();
        ExercisePlan plan = planMapper.selectById(p_id);
        List<NewTable> tableList = plan.getTableList();
        List<StrengthData> dataList = plan.getStrengthList();
        if(plan != null){
            for (StrengthData data : dataList){
//                System.out.println(data.getP_id());
                dataMapper.deleteStrengthDataByPID(data);
            }
            for(NewTable table : tableList){
                List<NewLine> lineList = table.getLineList();
                for(NewLine line : lineList){
                    lineMapper.deleteNewLineByTableID(line);
                }
                tableMapper.deleteNewTableByPID(table);
            }
            planMapper.deleteExercisePlan(plan);
            result.setCode(200);
            result.setData(1);
            result.setMessage("成功删除");
        }else {
            result.setCode(500);
            result.setData(0);
            result.setMessage("删除失败");
        }
        return result;
    }
    @Override
    public Result<Integer> finishExercisePlan(String p_id,String c_id){
        Result<Integer> result = new Result<>();
        String custom_id = planMapper.selectById(p_id).getC_id();
        if(custom_id.equals(c_id)){
            ExercisePlan plan = planMapper.selectById(p_id);
            if(planMapper.finishPlan(plan) != null){
                result.setCode(200);
                result.setData(planMapper.finishPlan(plan));
                result.setMessage("已完成");
            }else {
                result.setCode(500);
                result.setData(0);
                result.setMessage("未完成");
            }
        }
        return result;
    }

    @Override
    public Result<Save> listSave(String c_id){
        Result<Save> result = new Result<>();
        result.setCode(200);
        result.setData(saveMapper.listExercisePlanByCID(c_id));
        result.setMessage("查询成功");
        return result;
    }
    @Override
    public Result<String> savePlans(Save save){
        Result<String> result = new Result<>();
        saveMapper.createExercisePlan(save);

        if(save.getStrengthList()!=null && save.getStrengthList().size()>0){
            List<SaveSD> dataList = save.getStrengthList();
            for(SaveSD data : dataList){
                data.setSave_id(save.getSave_id());
                sdMapper.createDataBatch(data);
            }
        }
//        自定义表格插入
        if(save.getTableList()!=null && save.getTableList().size()>0){
            List<SaveTable> tableList = save.getTableList();
            for(SaveTable table : tableList){
                table.setSave_id(save.getSave_id());
                saveTableMapper.saveTable(table);
                List<SaveLine> lineList = table.getSlineList();
                for(SaveLine line : lineList){
                    line.setStable_id(table.getStable_id());
                }
                saveLineMapper.saveLineBatch(lineList);
            }
        }

        result.setCode(200);
        result.setData(save.getSave_id());
        result.setMessage("插入成功");
        return  result;
    }
//    @Override
//    public Result<Integer> saveStrengthData(List<SaveSD> dataList, String save_id){
//        Result<Integer> result = new Result<>();
//        for(SaveSD data : dataList){
//            data.setSave_id(save_id);
//            sdMapper.createDataBatch(data);
//        }
//        result.setCode(200);
//        result.setData(1);
//        result.setMessage("插入成功");
//        return result;
//    }
//    @Override
//    public Result<Integer> saveNewTable(List<SaveTable> tableList ,String save_id){
//        Result<Integer> result = new Result<>();
//
//        for(SaveTable table : tableList){
//            table.setSave_id(save_id);
//            saveTableMapper.saveTable(table);
//            List<SaveLine> lineList = table.getSlineList();
//            for(SaveLine line : lineList){
//                line.setStable_id(table.getStable_id());
//            }
//            saveLineMapper.saveLineBatch(lineList);
//        }
//        result.setCode(200);
//        result.setData(1);
//        result.setMessage("插入成功");
//        return result;
//    }
//    @Override
//    public Result<Integer> deleteSave(String save_id){
//        Result<Integer> result = new Result<>();
//        Save save = saveMapper.selectById(save_id);
//        List<SaveTable> tableList = save.getTableList();
//        List<SaveSD> dataList = save.getStrengthList();
//        if(save != null){
//            for (SaveSD data : dataList){
////                System.out.println(data.getP_id());
//                sdMapper.deleteStrengthDataBySaveID(data);
//            }
//            for(SaveTable table : tableList){
//                List<SaveLine> lineList = table.getSlineList();
//                for(SaveLine line : lineList){
//                    saveLineMapper.deleteNewLineByTableID(line);
//                }
//                saveTableMapper.deleteTableBySaveID(table);
//            }
//            saveMapper.deleteExercisePlan(save);
//            result.setCode(200);
//            result.setData(1);
//            result.setMessage("成功删除");
//        }else {
//            result.setCode(500);
//            result.setData(null);
//            result.setMessage("删除失败");
//        }
//        return result;
//    }
    @Override
    public Result<Integer> updateSave(Save save){
        Result<Integer> result = new Result<>();
        List<SaveTable> tableList = save.getTableList();
        List<SaveSD> sdList = save.getStrengthList();

        for(SaveSD data : sdList){
            sdMapper.updateStrengthData(data);
        }
        for(SaveTable data : tableList){
            for(SaveLine line : data.getSlineList()){
                saveLineMapper.updateNewLine(line);
            }
            saveTableMapper.updateNewTable(data);
        }
        result.setCode(200);
        result.setData(saveMapper.updateSave(save));
        result.setMessage("修改成功");
        return result;
    }
//    @Override
//    public Result<Integer> updateStrengthData(List<SaveSD> saveSDList){
//        Result<Integer> result = new Result<>();
//
//        result.setCode(200);
//        result.setData(1);
//        result.setMessage("修改成功");
//        return result;
//    }
//    @Override
//    public Result<Integer> updateNewTable(List<SaveTable> saveTableList){
//        Result<Integer> result = new Result<>();
//
//        result.setCode(200);
//        result.setData(1);
//        result.setMessage("修改成功");
//        return result;
//    }
}